/**
 * 优化1(冷热消息分区):
 * 热消息：登录后的消息
 * 冷消息: 登录前的消息
 * 每个会话的冷热消息分别用一个key进行存储，当有新的消息时，只更新热消息key，冷消息key保持不变
 * 由于热消息数量不会很大，所以localForage.setItem耗时很低，可以防止消息过多时出现卡顿的情况
 *
 * 优化2(延迟渲染):
 * 拉取消息时，如果直接用state.chats接收，页面就开始渲染，一边渲染页面一边大量接消息会导致很严重的卡顿
 * 为了加速拉取离线消息效率，拉取时消息暂时存储到cacheChats,等待所有离线消息拉取完成后，再统一放至state中进行渲染
 *
 * 优化3(pinia代替vuex)
 * 实测pinia的远超vuex,且语法更简洁清晰
 *
 * */
import { MESSAGE_TYPE, MESSAGE_STATUS } from "@/utils/enums";
export const useChatStore = defineStore("chat", {
  state: () => {
    return {
      activeChat: null, // 当前聊天对象
      privateMsgMaxId: 0, // 私聊最大id
      groupMsgMaxId: 0, // 群聊最大id
      loadingPrivateMsg: false, // 加载私聊中
      loadingGroupMsg: false, // 加载群聊中
      chats: [
        {
          delete: false,
          showName: "123",
          id: 2,
          type: "PRIVATE",
          headImage: "",
          targetId: 3,
          unreadCount: 4,
          sendNickName: "张媛",
          lastContent:
            "为了加速拉取离线消息效率，拉取时消息暂时存储到cacheChats,等待所有离线消息拉取完成后",
          messages: ["第一条", "第二条"],
          lastSendTime: "2024-07-28",
        },
        {
          delete: false,
          showName: "吖吖",
          id: 2,
          type: "GROUP",
          headImage: "",
          targetId: 3,
          unreadCount: 4,
          sendNickName: "张媛",
          lastContent:
            "为了加速拉取离线消息效率，拉取时消息暂时存储到cacheChats,等待所有离线消息拉取完成后",
          messages: ["第一条", "第二条"],
          lastSendTime: "2024-07-28",
        },
      ] as any, // 聊天列表
    };
  },
  actions: {
    // 设置当前聊天对象
    setActiveChat(idx: number) {
      this.activeChat = this.chats[idx];
    },
    // 删除聊天
    removeChat(idx: number) {
      //   this.chats.splice(idx, 1);
      let chats = this.chats;
      if (chats[idx] == this.activeChat) {
        this.activeChat = null;
      }
      chats[idx].delete = true;
      chats[idx].stored = false;
    },
    // 聊天置顶
    moveTop(idx: number) {
      if (idx > 0) {
        let chat = this.chats[idx];
        this.chats.splice(idx, 1);
        this.chats.unshift(chat);
        chat.lastSendTime = new Date().getTime();
        chat.stored = false;
      }
    },
    // 置顶未读数量
    resetUnreadCount(chatInfo: any) {
      let chats = this.chats;
      for (let idx in chats) {
        if (
          chats[idx].type == chatInfo.type &&
          chats[idx].targetId == chatInfo.targetId
        ) {
          chats[idx].unreadCount = 0;
          chats[idx].atMe = false;
          chats[idx].atAll = false;
          chats[idx].stored = false;
          break;
        }
      }
    },
    //插入消息
    insertMessage(msgInfo: any, chatInfo: any) {
      let time = new Date().getTime();
      let type = chatInfo.type;
      // 记录消息的最大id
      if (
        msgInfo.id &&
        type == "PRIVATE" &&
        msgInfo.id > this.privateMsgMaxId
      ) {
        this.privateMsgMaxId = msgInfo.id;
      }
      if (msgInfo.id && type == "GROUP" && msgInfo.id > this.groupMsgMaxId) {
        this.groupMsgMaxId = msgInfo.id;
      }
      // 如果是已存在消息，则覆盖旧的消息数据
      let chat = this.findChat(chatInfo);
      let message = this.findMessage(chat, msgInfo);
      if (message) {
        Object.assign(message, msgInfo);
        chat.stored = false;
        this.saveToStorage();
        return;
      }
      // 插入新的数据
      if (msgInfo.type == MESSAGE_TYPE.IMAGE) {
        chat.lastContent = "[图片]";
      } else if (msgInfo.type == MESSAGE_TYPE.FILE) {
        chat.lastContent = "[文件]";
      } else if (msgInfo.type == MESSAGE_TYPE.AUDIO) {
        chat.lastContent = "[语音]";
      } else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VOICE) {
        chat.lastContent = "[语音通话]";
      } else if (msgInfo.type == MESSAGE_TYPE.ACT_RT_VIDEO) {
        chat.lastContent = "[视频通话]";
      } else if (
        msgInfo.type == MESSAGE_TYPE.TEXT ||
        msgInfo.type == MESSAGE_TYPE.RECALL ||
        msgInfo.type == MESSAGE_TYPE.TIP_TEXT
      ) {
        chat.lastContent = msgInfo.content;
      }
      chat.lastSendTime = msgInfo.sendTime;
      chat.sendNickName = msgInfo.sendNickName;
      // 未读加1
      if (
        !msgInfo.selfSend &&
        msgInfo.status != MESSAGE_STATUS.READED &&
        msgInfo.status != MESSAGE_STATUS.RECALL &&
        msgInfo.type != MESSAGE_TYPE.TIP_TEXT
      ) {
        chat.unreadCount++;
      }
      // 是否有人@我
      if (
        !msgInfo.selfSend &&
        chat.type == "GROUP" &&
        msgInfo.atUserIds &&
        msgInfo.status != MESSAGE_STATUS.READED
      ) {
        let userStore = useUserStore();
        let userId = userStore.userInfo.id;
        if (msgInfo.atUserIds.indexOf(userId) >= 0) {
          chat.atMe = true;
        }
        if (msgInfo.atUserIds.indexOf(-1) >= 0) {
          chat.atAll = true;
        }
      }
      // 间隔大于10分钟插入时间显示
      if (
        !chat.lastTimeTip ||
        chat.lastTimeTip < msgInfo.sendTime - 600 * 1000
      ) {
        chat.messages.push({
          sendTime: msgInfo.sendTime,
          type: MESSAGE_TYPE.TIP_TIME,
        });
        chat.lastTimeTip = msgInfo.sendTime;
      }
      // 根据id顺序插入，防止消息乱序
      let insertPos = chat.messages.length;
      // 防止 图片、文件 在发送方 显示 在顶端  因为还没存库，id=0
      if (msgInfo.id && msgInfo.id > 0) {
        for (let idx in chat.messages) {
          if (chat.messages[idx].id && msgInfo.id < chat.messages[idx].id) {
            insertPos = idx;
            console.log(
              `消息出现乱序,位置:${chat.messages.length},修正至:${insertPos}`
            );
            break;
          }
        }
      }
      chat.messages.splice(insertPos, 0, msgInfo);
      chat.stored = false;

      console.log("耗时:", new Date().getTime() - time);
    },
  },
});
